package com.kirk.cts.core.launcher;

import com.kirk.cts.core.constants.SystemConstants;
import com.kirk.cts.core.context.CrawlerToolContextData;
import org.apache.commons.lang.StringUtils;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 * <p> SpringLauncherImpl.java </p>
 *
 * @version 1.0.0
 * @Author kirkliu
 * @Date 2020-08-29 22:22
 * @Description ILauncher接口Spring实现类, 负责加载Spring配置文件
 */
public class SpringLauncherImpl implements ILauncher {


    @Override
    public void launch() {
        Map<String, Map<String, String>> plugins = CrawlerToolContextData.getInstance().getPlugins();
        List<String> activePlugins = new ArrayList<>(10);
        activePlugins.add("spring/applicationContext.xml");
        String key = "";
        String[] tempPaths = null;
        for (Entry<String, Map<String, String>> entry : plugins.entrySet()) {
            // 插件处于激活状态  Active=true
            if (Boolean.valueOf(entry.getValue().get(SystemConstants.PLUGIN_PROPERTIES_KY_ACTIVE))) {
                // BeanXmlPath 是否配置
                if (StringUtils.isNotBlank(entry.getValue().get(SystemConstants.PLUGIN_PROPERTIES_KY_BEANXMLPATH))) {
                    // 获取路径 BeanXmlPath 多个逗号分隔
                    tempPaths = entry.getValue().get(SystemConstants.PLUGIN_PROPERTIES_KY_BEANXMLPATH).split(",");
                    for (String path : tempPaths) {
                        activePlugins.add(path);
                    }
                }
            }
        }
        int i = 0;
        String[] contextPaths = new String[activePlugins.size()];
        for (String xmlPath : activePlugins) {
            contextPaths[i] = xmlPath;
            i++;
        }
        CrawlerToolContextData.getInstance().setApplicationContext(new ClassPathXmlApplicationContext(contextPaths));
    }


}
